package server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.swing.JTable;
import javax.swing.JTextArea;

import common.SendMess;

public class ServerThread extends Thread{
    private ServerSocket ss;
    private int port;
    private InetAddress ip;
    private MyTextArea logs;
    private JTable table;
    private JDBC db;
    
    Map<UUID, Worker> allClient = new HashMap<UUID, Worker>();

    public ServerThread(int port, InetAddress ip, MyTextArea logs, JTable table)
    {
        this.port = port;
        this.ip = ip;
        this.logs = logs;
        this.table = table;
	    if(db == null)
	    {
	    	db = new JDBC(logs,null,table);
	    	db.start();
	    }
	    else
	    {
	    	logs.Append("DataBase has already connected");
	    }
    }
    @Override
    public void run() {
        try{
            Socket cs;
            ss = new ServerSocket(port, 0, ip);
            logs.Append("Server start on port= "+port+" and ip="+ip.getHostAddress());
            while (true){
            	logs.Append("Waiting of clients...");
                cs = ss.accept();
                logs.Append("Client connect");
                UUID id = UUID.randomUUID();
                Worker w = new Worker(cs, this, logs, id,table,db);
                allClient.put(id, w);
                w.start();
            }
        } catch(IOException e){
            logs.Append(e.getMessage());
            logs.Append("Server crashed");
        }
    }
    
    public void unlink(UUID id){
    	logs.Append("Client with UUID= " + id + "unlinked");
        allClient.remove(id);
    }
    
    public void stopServer(){
    	
        Iterator<Worker> itr = allClient.values().iterator();
        while(itr.hasNext()){
            itr.next().stop();
        }
        logs.Append("All clients(workers) were stopped");
        try{
            ss.close();
        } catch(IOException e){
            logs.Append(e.getMessage());
        }
        logs.Append("Server finished");
        this.stop();
    }
    
}

